package youcaihuaoa.weetop.com.ui.apply

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.PathUtils
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.just.agentweb.PermissionInterceptor
import com.robot.base.base.activity.GLBaseActivity
import com.robot.base.configs.AppConstants
import com.robot.base.model.CustomProfileItemBean
import com.robot.base.util.UriUtils
import youcaihuaoa.weetop.com.BR
import youcaihuaoa.weetop.com.R
import youcaihuaoa.weetop.com.databinding.AppActivityTrendApplyProfileBinding
import youcaihuaoa.weetop.com.ui.adapter.FolderInfoAdapter
import youcaihuaoa.weetop.com.ui.adapter.MyApplyProfileAdapter
import youcaihuaoa.weetop.com.ui.adapter.TrendApplyProfileAdapter
import youcaihuaoa.weetop.com.vm.apply.TrendApplyProfileViewModel
import java.io.File

@Route(path = AppConstants.Router.Main.A_TREND_APPLY_PROFILE)
class TrendApplyProfileActivity :
    GLBaseActivity<AppActivityTrendApplyProfileBinding, TrendApplyProfileViewModel>() {

    var id = ""
    var zdy_form_id = ""
    var title = ""
    var type = ""
    var status = 0

    private lateinit var trendApplyProfileAdapter: TrendApplyProfileAdapter
    private lateinit var applyAdapter: MyApplyProfileAdapter
    private lateinit var folderInfoAdapter: FolderInfoAdapter

    override fun initComponents() {
        addSingleTitleBar(title)
        applyAdapter = MyApplyProfileAdapter()
        trendApplyProfileAdapter = TrendApplyProfileAdapter()
        folderInfoAdapter = FolderInfoAdapter(status == 2)
        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(this@TrendApplyProfileActivity)
            adapter = applyAdapter
        }

        binding.mRvOther.apply {
            layoutManager = LinearLayoutManager(this@TrendApplyProfileActivity)
            adapter = trendApplyProfileAdapter
        }

        binding.mRvFolderInfo.apply {
            layoutManager = GridLayoutManager(this@TrendApplyProfileActivity, 2)
            adapter = folderInfoAdapter
        }
    }

    private fun initPermission() {
        XXPermissions.with(this)
            .permission(
                Permission.READ_EXTERNAL_STORAGE,
                Permission.WRITE_EXTERNAL_STORAGE
            )
            // 申请多个权限
            // 设置不触发错误检测机制（局部设置）
            //.unchecked()
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, all: Boolean) {
                    UriUtils.skipFile(this@TrendApplyProfileActivity)
                }

                override fun onDenied(permissions: MutableList<String>, never: Boolean) {
                    showToast("部分权限未授权，影响功能使用")
                }
            })
    }

    override fun initContentView(savedInstanceState: Bundle?): Int =
        R.layout.app_activity_trend_apply_profile

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewObservable() {
        viewModel.uiEvent.menuDataLiveEvent.observe(this) {
            val examineData = it.examine_data
            applyAdapter.setNewInstance(examineData)
            val endBean = CustomProfileItemBean()
            endBean.title = "完成"
            applyAdapter.addData(endBean)
            trendApplyProfileAdapter.setNewInstance(it.str_data)
        }

        viewModel.uiEvent.updateFileEvent.observe(this) {
            folderInfoAdapter.status = (status == 2 || viewModel.complete.get() == true)
            LogUtils.e(status == 2 , viewModel.complete.get() == true)
            folderInfoAdapter.addData(it)
        }
        viewModel.uiEvent.skipFileEvent.observe(this) {
            initPermission()
        }

        viewModel.uiEvent.confirmEvent.observe(this) {
            val mapList = mutableListOf<Map<String, String?>>()
            trendApplyProfileAdapter.data.forEach {
                if(!TextUtils.isEmpty(it.text)) {
                    val map = mapOf(
                        "title" to it.title,
                        "value" to it.text,
                        "status" to it.status
                    )
                    mapList.add(map)
                }
            }
            val jbcs_fj_path = StringBuffer()
            folderInfoAdapter.data.forEach {
                jbcs_fj_path.append(it.file_path).append(";")
            }
            LogUtils.e(jbcs_fj_path)
            if (jbcs_fj_path.isNotEmpty()) {
                jbcs_fj_path.deleteCharAt(jbcs_fj_path.length - 1)
            }
            viewModel.templateWholeCustomAdd(
                if (viewModel.status.get() == 0) {
                    "1"
                } else {
                    "2"
                }, jbcs_fj_path.toString(), mapList
            )
        }
    }

    override fun initData() {
        viewModel.type = type
        viewModel.initData(status, id, zdy_form_id)
    }

    override fun initParam() {
        zdy_form_id = intent.getStringExtra(AppConstants.BundleKey.ZDY_FORM_ID) ?: ""
        id = intent.getStringExtra(AppConstants.BundleKey.ID) ?: ""
        title = intent.getStringExtra(AppConstants.BundleKey.TITLE) ?: ""
        type = intent.getStringExtra(AppConstants.BundleKey.TYPE) ?: ""
        status = intent.getIntExtra(AppConstants.BundleKey.STATUS, 0)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            val uri: Uri? = data!!.data
            if (uri != null) {
                if ("file".equals(uri.scheme, ignoreCase = true)) { //使用第三方应用打开
                    val path = uri.path
                    viewModel.uploadFile(File(path))
                    return
                }
                LogUtils.e(uri)
                val path = UriUtils.getPath(this, uri)
                LogUtils.e(path)
                viewModel.uploadFile(File(path))
            }
        }
    }
}